const fs = require('fs');
const Module = require('./module');
const MagicString = require("magic-string");

class Bundle {
  constructor(options) {
    //确保入口文件以 .js 结尾
    this.entryPath = options.entry.replace(/\.js$/, '') + '.js';

    this.modules = {}; //存放着所有模块 (入口文件和它依赖的模块)
  }

  build(outputFileName){
    //从入口文件的绝对路径触发找到它的模块定义
    const entryModule = this.fetchModule(this.entryPath);

    //把这个入口模块所有的语句进行展开, 返回所有的语句组成的数组
    this.statements = entryModule.expandAllStatements();
    const {code} = this.generate();
    fs.writeFileSync(outputFileName, code, 'utf-8');
  }

  //获取模块信息
  fetchModule(importee){
    const route = importee;
    if (route) {
      const code = fs.readFileSync(route, 'utf-8');
      const module = new Module({
        code, //模块源代码
        path: route, //模块的绝对路径
        bundle: this //属于哪个bundle
      });
      return module;
    }
  }

  generate(){
    const magicString = new MagicString.Bundle();
    this.statements.forEach(statement => {
      const source = statement._source.clone();
      magicString.addSource({
        content: source,
        separator: '\n'
      });
    });
    return {code: magicString.toString()};
  }
}

module.exports = Bundle
